<template>
  <div class="email-container">
    <!-- 私信列表区域 -->
    <div class="conversations">
      <div v-for="conversation in conversations" :key="conversation.id" class="conversation" @click="goToConversation(conversation)">
        <img :src="'http://localhost:8080/images/upload/' + conversation.targetUser.profile_picture" class="avatar" alt="avatar">
        <div class="conversation-info">
          <div class="name">{{ conversation.targetUser.user_name }}</div>
          <div class="message">{{ conversation.lastMessageContent }}</div>
          <div class="time">{{ conversation.lastMessageTime }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { ElMessage } from "element-plus";

export default {
  data() {
    return {
      userId: this.$route.params.user_id, // 当前用户ID
      conversations: [], // 存储私信列表
    };
  },
  created() {
    this.fetchConversations();
  },
  methods: {
    async fetchConversations() {
      try {
        const response = await axios.get(`http://localhost:8080/messages/conversation/${this.userId}`);
        this.conversations = response.data;
      } catch (error) {
        console.error("获取私信列表失败", error);
        ElMessage.error("获取私信列表失败，请检查网络连接");
      }
    },
    goToConversation(conversation) {
      // 跳转到私聊页面，使用路由params传递用户ID
      this.$router.push({
        name: 'private-message',
        params: {
          user_id: this.userId,
          targetUser_id: conversation.targetUser.id // 确保后端返回的conversation对象中包含targetUser.id属性
        }
      });
    },
  },
};
</script>

<style scoped>
.email-container {
  display: flex;
  flex-direction: column;
  padding: 10px;
  background-color: #f5f5f5;
}

.conversations {
  display: flex;
  flex-direction: column;
}

.conversation {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #e0e0e0;
  cursor: pointer;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.conversation-info {
  flex-grow: 1;
}

.name {
  font-weight: bold;
}

.message {
  color: #666;
}

.time {
  color: #999;
  font-size: 12px;
}
</style>